import os
import base64

import httpx

from fastapi import FastAPI
from langchain_openai import AzureChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser, XMLOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langserve import add_routes
from pydantic import BaseModel, Field

os.environ["http_proxy"] = "127.0.0.1:7890"
os.environ["https_proxy"] = "127.0.0.1:7890"
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "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"

os.environ["AZURE_OPENAI_ENDPOINT"] = "http://menshen.test.xdf.cn"
os.environ["OPENAI_API_KEY"] = "c8575027653b42b1b47747f0b4ab135b"
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_VERSION"] = "2023-05-15"

llm = AzureChatOpenAI(
    deployment_name="gpt-4o",
    model_name="gpt-4o",
    temperature=0)


xml_parser = XMLOutputParser(tags=["versions", "version", "date"])

prompt = ChatPromptTemplate.from_template(
    "{question}，\n请按照如下 XML 格式输出结果。\n{xml_instruction}\n注意：必须使用 XML 格式，不要使用 JSON！"
    # ,partial_variables={"xml_instruction": xml_parser.get_format_instructions()}
)


chain = prompt.partial(xml_instruction=xml_parser.get_format_instructions()) | llm | xml_parser

resp = chain.invoke({"question": "请把langchain的版本都列出来，并且按照发布的时间排序"})
print(resp)
# for s in chain.stream({"question": "请把langchain的版本都列出来，并且按照发布的时间排序"}):
#     print(s)
